import { getData, setData } from './dataStore';
import { isValidToken } from './check';

export const transferQuizToAnother = (token: string, userEmail: string, quizId: number) => {
    const data = getData();
    const authUserId = isValidToken(token);
    if (!authUserId) {
        return { error: 'Token is empty or invalid (does not refer to valid logged in user session)' };
    }

    const currentUser = data.users.find(user => user.userID === authUserId);
    const targetUser = data.users.find(user => user.email === userEmail);

    if (!currentUser) {
        return { error: 'Invalid authUserId' };
    }
    if (currentUser.email === userEmail) {
        return { error: 'userEmail is the current logged in user' };
    }
    if (!targetUser) {
        return { error: 'userEmail is not a real user' };
    }

    const quiz = data.quizzes.find(q => q.QuizID === quizId);
    if (!quiz) {
        return { error: 'Quiz ID does not refer to a valid quiz.' };
    }
    if (!quiz.AuthorID.includes(currentUser.userID)) {
        return { error: 'Quiz ID does not refer to a quiz that this user owns.' };
    }
    if (quiz.AuthorID.includes(targetUser.userID)) {
        return { error: 'Quiz ID refers to a quiz that is already owned by the target user' };
    }
    if (quiz.State === 'END') {
        return { error: 'Quiz is in an END state and cannot be transferred' };
    }

    quiz.AuthorID = [targetUser.userID];
    setData(data);

    return { message: 'Success!' };
};